package validator

import (
	"errors"
	"unicode"
)

const (
	PASSLENMIN = 6
	PASSLENMAX = 15
)

var (
	ErrInValidPassword = errors.New("invalid password format")
	ErrPassErrLong     = errors.New("the password length must be greater than or equal to 6 and less than 15")
	ErrPasswordEasy    = errors.New("password too simple")

	// 密码必须包含数字 + 字母 + 特殊字符 + 不能空格
	// passRegex = regexp.MustCompile(`^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*()_+=\[\]{};':"\\|,.<>\/?-])(?!.*\s).{8,}$`)
)

var commonEasyPass = map[string]bool{
	"password":    true,
	"12345678":    true,
	"adminpass":   true,
	"password123": true,
}

type PassValiadtor struct {
	passLenMin int
	passLenMax int
}

func NewPassValiadtor() *PassValiadtor {
	return &PassValiadtor{
		passLenMin: PASSLENMIN,
		passLenMax: PASSLENMAX,
	}
}

func (p *PassValiadtor) Validate(password string) error {
	if len(password) < p.passLenMin && len(password) > p.passLenMax {
		return ErrPassErrLong
	}

	if commonEasyPass[password] {
		return ErrPasswordEasy
	}

	var (
		hasDigit       bool
		hasLetter      bool
		hasSpecialChar bool
		hasSpace       bool
	)

	for _, char := range password {
		switch {
		case unicode.IsDigit(char):
			hasDigit = true
		case unicode.IsLetter(char):
			hasLetter = true
		case unicode.IsSymbol(char) || unicode.IsPunct(char):
			hasSpecialChar = true
		case unicode.IsSpace(char):
			hasSpace = true
		}
	}

	if !hasDigit || !hasLetter || !hasSpecialChar || hasSpace {
		return ErrInValidPassword
	}
	return nil
}

func IsValidPass(password string) (bool, error) {
	validator := NewPassValiadtor()
	err := validator.Validate(password)
	return err == nil, err
}
